package com.dishi.hj212.server;

import com.dishi.hj212.handler.EPServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;

/**
 * @author ds
 * @Describe 环保设备对接程序启动类，Netty服务器端启动类，接收设备上传的数据。
 * @Date
 */
@Slf4j
@Component
public class EPServer implements ApplicationRunner {

    /**
     * 分发线程组
     */
    private static final EventLoopGroup bossGroup = new NioEventLoopGroup(2);
    /**
     * 工作线程组
     */
    private static final EventLoopGroup workerGroup = new NioEventLoopGroup(4);
    /**
     * Netty服务端监听的端口号
     */
    @Value("${eps.port}")
    private String port;
    @Value("${eps.address}")
    private String address;

    /**
     * 关闭服务
     */
    public static void shutdown() {
        // 优雅关闭
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }

    /**
     * 启动服务
     */
    public void runEPServer() {
        log.info("===== EP Netty Server start =====");
        try {
            ServerBootstrap b = new ServerBootstrap();
            //创建事件循环组
            b.group(bossGroup, workerGroup);
            b.channel(NioServerSocketChannel.class);
            b.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) {
                    ChannelPipeline pipeline = ch.pipeline();
                    // 解决拆包问题
                    ByteBuf delimiter = Unpooled.copiedBuffer("\r\n", CharsetUtil.UTF_8);
                    pipeline.addLast(new DelimiterBasedFrameDecoder(2048, delimiter));

                    pipeline.addLast("serverDecoder", new StringDecoder(CharsetUtil.UTF_8));
                    pipeline.addLast("serverEncoder", new StringEncoder(CharsetUtil.UTF_8));

                    // netty提供了空闲状态监测处理器 0表示禁用事件
                    pipeline.addLast(new IdleStateHandler(65, 0, 0, TimeUnit.MINUTES));
                    pipeline.addLast(new EPServerHandler());
                }
            });
            log.info("环保 Netty Server PORT = " + port);
            b.bind(new InetSocketAddress(address, Integer.parseInt(port))).sync();

        } catch (Exception e) {
            e.printStackTrace();
            shutdown();
        }
    }

    @Override
    public void run(ApplicationArguments args) {
        // 启动环保监测Netty服务端
        runEPServer();
    }

}
